<?php
namespace app\job;

use app\api\controller\v1\Clue as ClueModel;
use think\Db;
use think\Exception;
use think\Queue;
use think\queue\Job;

//php think queue:listen --queue ClueZeroPrice
//第三步线索池挂空成本
class ClueZeroPrice{
    /**
     * fire方法是消息队列默认调用的方法
     * @param Job            $job      当前的任务对象
     * @param array|mixed    $data     发布任务时自定义的数据
     */
    public function fire(Job $job,$data){
        // 如有必要,可以根据业务需求和数据库中的最新数据,判断该任务是否仍有必要执行.
        $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
        if(!$isJobStillNeedToBeDone){
            $job->delete();
            return;
        }

        $isJobDone = $this->doHelloJob($data);

        if ($isJobDone) {
            //如果任务执行成功， 记得删除任务
            $job->delete();
        }else{
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
                $job->delete();
                // 也可以重新发布这个任务
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }


    /**
     * 有些消息在到达消费者时,可能已经不再需要执行了
     * @param array|mixed    $data     发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function checkDatabaseToSeeIfJobNeedToBeDone($data){
        return true;
    }

    /**
     * 根据消息中的数据进行实际的业务处理
     * @param array|mixed    $data     发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    private function doHelloJob($data) {
        try {
            $map1['is_chengben']=0;
            $map1['create_time']=$data['time'];
            $map2['clue_time']=$data['time'];

            Db::name('clue_zero_cost_details')->where($map2)->delete();

            $list=Db::name('clue')->alias('a')->field('a.id,city,pro_id,create_time')
                ->where($map1)->chunk(20,function($users) {
                    $log=[];
                    foreach ($users as $user) {
                        $dateTime=date('Y-m-d',$user['create_time']);
                        $total=model('ClueCostLog')->field('sum(money) money,sum(clue_num) clue_num,sum(true_consume) true_consume')->where(['city'=>$user['city'],'pro_id'=>$user['pro_id'],'time'=>$dateTime])->where('clue_num','>',0)->find();
                        if(!empty($total['clue_num'])){
                            $PriceZeroType=2;
                            //账户成本
                            $avgChangeMoney=bcdiv($total['money'],$total['clue_num'],2);
                            //真实
                            $avgConsume=bcdiv($total['true_consume'],$total['clue_num'],2);
                        }else{
                            $dday=date('Y-m-d',strtotime('-3 days',strtotime($dateTime)));
                            $whereMap['time']=['between',[$dday, $dateTime]];
                            $total=model('ClueCostLog')->field('sum(money) money,sum(clue_num) clue_num,sum(true_consume) true_consume')->where(['city'=>$user['city'],'pro_id'=>$user['pro_id']])->where($whereMap)->where('clue_num','>',0)->find();
                            if(!empty($total['clue_num'])){
                                //账户成本
                                $avgChangeMoney=bcdiv($total['money'],$total['clue_num'],2);
                                //真实
                                $avgConsume=bcdiv($total['true_consume'],$total['clue_num'],2);
                                $PriceZeroType=3;
                            }else{
                                $dday=date('Y-m-d',strtotime('-7 days',strtotime($dateTime)));
                                $whereMap['time']=['between',[$dday, $dateTime]];
                                $total=model('ClueCostLog')->field('sum(money) money,sum(clue_num) clue_num,sum(true_consume) true_consume')->where(['city'=>$user['city'],'pro_id'=>$user['pro_id']])->where($whereMap)->where('clue_num','>',0)->find();
                                if(!empty($total['clue_num'])){
                                    //账户成本
                                    $avgChangeMoney=bcdiv($total['money'],$total['clue_num'],2);
                                    //真实
                                    $avgConsume=bcdiv($total['true_consume'],$total['clue_num'],2);
                                    $PriceZeroType=4;
                                }else{
                                    $PriceZeroType=1;
                                    if ($user['pro_id']==4){//车
                                        $avgChangeMoney=110;
                                        $avgConsume=110;
                                    }elseif ($user['pro_id']==3){//房
                                        $avgChangeMoney=190;
                                        $avgConsume=190;
                                    }else{
                                        $avgChangeMoney=150;
                                        $avgConsume=150;
                                    }
                                }
                            }
                        }
                        if($avgChangeMoney>0){
                            $updatePrice['xz_price']=$avgChangeMoney;
                        }else{
                            $updatePrice['xz_price']=0;
                        }
                        if($avgConsume>0){
                            $updatePrice['xz_true_price']=$avgConsume;
                        }else{
                            $updatePrice['xz_true_price']=0;
                        }
                        $updatePrice['xz_price2']=0;
                        $updatePrice['xz_true_price2']=0;
                        Db::name('clue')->where('id',$user['id'])->update($updatePrice);
                        $log[]=['clue_id'=>$user['id'],'price'=>$avgChangeMoney,'true_price'=>$avgConsume,'create_time'=>time(),'clue_time'=>$user['create_time'],'type'=>$PriceZeroType];

                    }
                    if(!empty($log)){
                        Db::name('clue_zero_cost_details')->insertAll($log);
                    }
                });
            echo json_encode($data,JSON_UNESCAPED_UNICODE);
            $jobHandlerClassName  = 'app\job\ClueLossPrice@fire';
            // 2.当前任务归属的队列名称，如果为新队列，会自动创建
            $jobQueueName     = "ClueLossPrice";

            $jobData = ['time'=>$data['time']];//时间戳

            $isPushed = Queue::push($jobHandlerClassName, $jobData, $jobQueueName);
            return true;
        }catch (Exception $e){
            $errData=[
                'code'=>$e->getCode(),
                'msg'=>$e->getMessage(),
                'flie'=>$e->getFile(),
                'line'=>$e->getLine(),
            ];
            trace($errData,'error');
            return true;
        }
    }

}